package com.teradata.io.nio.buffer;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/14 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */
public class BufferDemo {

    public static void decode(String str) throws UnsupportedEncodingException {
        // 创建一个ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(128);
        // 向ByteBuffer中写模式，写入数据
        byteBuffer.put(str.getBytes("UTF-8"));
        // 反转为读模式
        byteBuffer.flip();

        /*对获取utf8的编码器*/
        Charset utf8 = Charset.forName("UTF-8");
        /*对byteBuffer中的内容解码*/
        CharBuffer charBuffer = utf8.decode(byteBuffer);

        char[] charArr = Arrays.copyOf(charBuffer.array(), charBuffer.limit());
        System.out.println(charArr);
    }

    public static void encode(String str) {
        CharBuffer charBuffer = CharBuffer.allocate(128);
        charBuffer.append(str);
        charBuffer.flip();

        Charset utf8 = Charset.forName("utf-8");
        ByteBuffer byteBuffer = utf8.encode(charBuffer);

        byte[] bytes = Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());
        System.out.println(Arrays.toString(bytes));
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        decode("沽泡学院");
        encode("沽泡学院");
    }

}
